Skip to main content

Simple Async

This example builds upon the simple addition scenario in the previous section. In this section, we simulated an asynchronous operation in the worker file. The simulated delay (100ms) represents any asynchronous operation that might occur in a real-world scenario, such as database queries, file I/O, or network requests.

index.js
'use strict';

const Piscina = require('../..');
const { resolve } = require('path');

const piscina = new Piscina({
filename: resolve(__dirname, 'worker.js')
});

(async function () {
const result = await piscina.run({ a: 4, b: 6 });
console.log(result); // Prints 10
})();
worker.js
'use strict';

const { promisify } = require('util');
const sleep = promisify(setTimeout);

module.exports = async ({ a, b }) => {
// Fake some async activity
await sleep(100);
return a + b;
};

You can also check out this example on github.